import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import type { TabPaneName } from "element-plus";

interface TabsItemType {
  title: string;
  name: string;
}

export const useTabs = defineStore('tabs', () => {
  const editableTabsValue = ref("");
  const editableTabs = ref<TabsItemType[]>([]);

  const addTab = (path: string, title: string) => {
    const arr = editableTabs.value.filter(item => {
      return item.name === path
    })
    if (!arr.length) {
      editableTabs.value.push({
        title: title,
        name: path,
      });
    }
    editableTabsValue.value = path;
  };
  const removeTab = (targetName: TabPaneName) => {
    const tabs = editableTabs.value;
    let activeName = editableTabsValue.value;
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.name;
          }
        }
      });
    }

    editableTabsValue.value = activeName;
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName);
  };

  return {editableTabsValue, editableTabs, addTab, removeTab}
})
